<template>
  <el-card class="form-container" shadow="never">
    <el-form ref="categoryForm" :model="categoryForm" :rules="categoryRules" label-width="100px">
      <el-form-item label="分类名称:" prop="name">
        <el-input v-model="categoryForm.name" placeholder="请输入内容" />
      </el-form-item>
      <el-form-item>
        <el-button v-if="!isEdit" type="primary" @click="handleAddCategory">添加</el-button>
        <el-button v-if="isEdit" type="primary" @click="handleUpdateCategory">更新</el-button>
        <el-button v-if="isEdit" @click="resetForm('categoryForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import { getCategoryById, addCategory, updateCategory } from '@/api/category'

const defaultCategoryForm = {
  name: ''
}
export default {
  name: 'CategoryDetail',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      categoryForm: Object.assign({}, defaultCategoryForm),
      categoryRules: {
        name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    if (this.isEdit) {
      getCategoryById(this.$route.query.id).then(res => {
        this.categoryForm = res.data
      })
    } else {
      this.categoryForm = Object.assign({}, defaultCategoryForm)
    }
  },
  methods: {
    handleAddCategory() {
      this.$refs.categoryForm.validate(valid => {
        if (valid) {
          this.$confirm('是否要进行添加操作?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            addCategory(this.categoryForm).then(res => {
              this.$message.success('添加成功')
            })
          })
        } else {
          this.$message.error('未填写完全')
          return false
        }
      })
    },
    handleUpdateCategory() {
      this.$refs.categoryForm.validate(valid => {
        if (valid) {
          this.$confirm('是否要进行更新操作?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            updateCategory(this.categoryForm).then(res => {
              this.$message.success('更新成功')
            })
          })
        } else {
          this.$message.error('未填写完全')
          return false
        }
      })
    },
    resetForm(formName) {
      // console.info("reset")
      this.$refs[formName].resetFields()
      this.categoryForm = Object.assign({}, defaultCategoryForm)
    }
  }
}
</script>
<style lang="scss">
.form-container {
  .el-input__inner {
    width: 30%;
  }
}
</style>
